package com.xunhang.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunhang.dto.Result;
import com.xunhang.entity.Admin;
import com.xunhang.mapper.AdminMapper;
import com.xunhang.service.IAdminService;
import com.xunhang.utils.AdminHolder;
import com.xunhang.utils.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.xunhang.utils.Constants.*;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public Result login(Admin admin){
        if(admin==null||admin.getId()==null||admin.getPassword()==null||admin.getPassword().isEmpty()){
            return Result.fail("参数错误");
        }

        String rawPassword = admin.getPassword();
        String encodedPassword=getBaseMapper().selectById(admin.getId()).getPassword();

        if(PasswordEncoder.matches(encodedPassword,rawPassword)){
            Map<String,Object> map = new HashMap<>();
            map.put("id",admin.getId());
            String token = JWTUtil.createToken(map, SECRETT_CODE.getBytes());
            stringRedisTemplate.opsForValue().set(TOKEN_KEY+token,"1",TOKEN_TTL, TimeUnit.MINUTES);
            return Result.ok(token);
        }else {
            return Result.fail("用户名或密码错误");
        }
    }

    public Result logout(){
        String token= AdminHolder.getToken();
        stringRedisTemplate.delete(TOKEN_KEY+token);
        return Result.ok();
    }

    public Result register(Admin admin){
        if(admin.getName()==null){
            admin.setName(RandomUtil.randomString(16));
        }
        String rawPassword = admin.getPassword();
        String encodedPassword=PasswordEncoder.encode(rawPassword);
        admin.setPassword(encodedPassword);
        super.save(admin);
        return Result.ok(admin);
    }

}
